#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/7/18 11:04
# @Author  : 王凯
# @File    : qcwy_demo.py
# @Project : scrapy_spider
import hashlib
import hmac
import ssl
import time
from urllib.parse import quote

from requests.adapters import HTTPAdapter

from apps.jobs.jobs.middlewares import AcwScV2
from utils.proxies_tools import get_company_ip_crawler_by_api

hostname = "https://we.51job.com"
headers = {
    # "Accept": "application/json, text/plain, */*",
    "Accept-Language": "zh-CN,zh;q=0.9,zu;q=0.8,be;q=0.7,en;q=0.6",
    "Accept-Encoding": "gzip,deflate,br",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "From-Domain": "51job_web",
    "Origin": hostname,
    "Pragma": "no-cache",
    "Referer": hostname,
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-site",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
}
cupid_sign_key = "abfc8f9dcf8c3f3d8aa294ac5f2cf2cc7767e5592590f39c3f503271dd68562b"
company_name = "东莞市五方园信息科技有限公司"
timestamp = round(time.time())
route = (
    f"/api/job/search-pc?api_key=51job&timestamp={timestamp}"
    f"&keyword={quote(company_name)}&searchType=2&function=&industry="
    "&jobArea=000000&jobArea2=&landmark=&metro=&salary=&workYear=&degree=&companyType="
    "&companySize=&jobType=&issueDate=&sortType=0&pageNum=1&requestId=&pageSize=20&source=1&accountId=&"
    "pageCode=sou%7Csou%7Csoulb"
)
headers_sign = {
    "Sign": hmac.new(cupid_sign_key.encode("utf-8"), route.encode("utf-8"), digestmod=hashlib.sha256).hexdigest(),
}

import requests
from cryptography.hazmat.bindings.openssl.binding import Binding


class NewHTTPAdapter(HTTPAdapter):
    def __init__(self, pool_connections=10, pool_maxsize=10, max_retries=0, pool_block=False):
        super().__init__(
            pool_connections=pool_connections, pool_maxsize=pool_maxsize, max_retries=max_retries, pool_block=pool_block
        )

        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block, ssl_context=self.reset_ctx)

    @property
    def reset_ctx(self):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.options = Binding().lib.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
        return ctx

    def proxy_manager_for(self, *args, **kwargs):
        return super(NewHTTPAdapter, self).proxy_manager_for(*args, ssl_context=self.reset_ctx, **kwargs)


session = requests.session()
session.proxies = get_company_ip_crawler_by_api()
new_http_adapter = NewHTTPAdapter(pool_connections=1000, pool_maxsize=1000)
session.mount("http", new_http_adapter)
session.mount("https://", new_http_adapter)
headers = {'Accept-Language': 'zh-CN,zh;q=0.9,zu;q=0.8,be;q=0.7,en;q=0.6', 'Accept-Encoding': 'gzip,deflate,br', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'From-Domain': '51job_web',
           'Origin': 'https://we.51job.com', 'Pragma': 'no-cache', 'Referer': 'https://we.51job.com', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-site',
           'sign': '1e66045dce319146211422e7c493e6de392d91cb06ce38975d53a8a041af1748', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
           'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1) AppleWebKit/535.5.1 (KHTML, like Gecko) Version/4.0 Safari/535.5.1',
           'Proxy-Authorization': 'Basic c3F1aWQ6NzAyMjZmZjlmZjgxOGVkYmQ4MTZlOGMwNmI3NmVmOTc='}

# response = session.get(hostname + route, headers={**headers_sign, **headers})
# if "acw_sc__v2" in response.text:
#     cookie = AcwScV2(response).get_cookies()
#     session.cookies.update(cookie)
#     new_headers = {**headers_sign, **headers}
#
#     cookie_str = "; ".join([f"{k}={v}" for k, v in session.cookies.items()])
#
#     new_headers.update({"Cookie": cookie_str + f'; acw_tc={session.cookies.get("acw_tc")}'})
#     session.cookies.clear()
#     print(new_headers)
#     url = hostname + route
#     print(url)
#     print(headers)
#     response = session.get(url, headers=new_headers)
# print(response.text[:100])

url = "https://cupid.51job.com/open/noauth/company-info/pc-info?api_key=51job&timestamp=1721294677&encryCompanyId=UT9QN1cwBT8GZwRiVjA?ipcity__1361=eqIxyDnDRQDtitA5GNDQuhhE+DkQoNa4D"
url = "https://cupid.51job.com/open/noauth/company-info/pc-info?api_key=51job&timestamp=1721294677&encryCompanyId=UT9QN1cwBT8GZwRiVjA&ipcity__1361=eqIxyDnDRQDtitA5GNDQuhhE+DkQoNa4D"
print(session.get(url, headers=headers).content.decode()[:100])
